import { Dispatch, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import './App.css';
import { RootState } from './store';
import { updateState, delState, addTodos } from './store/action/todos'


function App() {
  // const todos = useSelector((state: { todos: { id: number, name: string, isDone: boolean }[] }) => state.todos)
  // const todos = useSelector<{ todos: [] }, { id: number, name: string, isDone: boolean }[]>(state => state.todos)
  const todos = useSelector((state: RootState) => state.todos)


  const dispatch = useDispatch<Dispatch<{ type: string, payload: any }>>()


  const refInput = useRef<HTMLInputElement>(null)

  // 改变状态
  const update = (id: number) => {
    // console.log(id);
    dispatch(updateState(id))
  }

  // 删除
  const del = (id: number) => {
    dispatch(delState(id))
  }

  // 添加
  const add = (e: any) => {
    console.log(e);
    if (refInput.current) {
      // console.log(refInput.current.value);
      dispatch(addTodos(refInput.current.value))
    }
  }

  // 回车事件
  const keyUP = (e: any) => {
    if (e.keyCode === 13 && refInput.current) {
      // const t = e.target as HTMLInputElement
      // dispatch(addTodos(t.value))
      dispatch(addTodos(refInput.current.value))
    }
  }


  return (
    <div className="App">
      <h1>todos</h1>
      <div>
        <input type="text" onKeyUp={keyUP} ref={refInput} />
        <button onClick={add} >添加</button>
      </div>
      <ul>
        {todos.map(item => <li key={item.id} style={{ listStyle: 'none' }}>
          {item.name} {item.isDone ? '已完成' : '未完成'}
          <button onClick={() => update(item.id)}>给我变</button>
          <button onClick={() => del(item.id)}>删除</button>
        </li>)}

      </ul>
    </div>
  );
}

export default App;
